package com.youlu.campus.admin.zm.utils;

import com.youlu.campus.admin.zm.req.ZmBaseMsgRequest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

/**
 * @author : [dengbo]
 * @className : ZmUtils
 * @description : [描述说明该类的功能]
 * @createTime : [2022/11/13 13:05]
 */
@Slf4j
public class ZmUtils {

    public static final String delimiter = "^^";

    public static String generateSignature(ZmBaseMsgRequest request, String secret) throws Exception {
        StringBuilder sb = new StringBuilder();
        sb.append("flow_id=" + request.getFlowId() + "&time=" + request.getTime() + secret);
        return MD5(sb.toString()).toLowerCase();
    }

    public static String generateSignature(Map<String, Object> data, String secret) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = (String[]) keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        int length = keyArray.length;
        for (int i = 0; i < length; ++i) {
            String k = keyArray[i];
            sb.append(k).append("=").append(data.get(k));
            if (i < length - 1) {
                sb.append("&");
            }
        }
        sb.append(secret);
        return MD5(sb.toString()).toLowerCase();
    }

    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        byte[] var4 = array;
        int var5 = array.length;

        for (int var6 = 0; var6 < var5; ++var6) {
            byte item = var4[var6];
            sb.append(Integer.toHexString(item & 255 | 256).substring(1, 3));
        }
        return sb.toString().toLowerCase();
    }

    @Data
    public static class ZmOpFlowInfo {
        private String openid;
        private Long flowId;
    }

    public static ZmOpFlowInfo getZmOpFlowInfo(String taskId) {
        int idx = taskId.indexOf("^^");
        String openId = taskId.substring(0, idx);
        String flowId = taskId.substring(idx + delimiter.length());
        ZmOpFlowInfo zmOpFlowInfo = new ZmOpFlowInfo();
        zmOpFlowInfo.setOpenid(openId);
        zmOpFlowInfo.setFlowId(Long.valueOf(flowId));
        return zmOpFlowInfo;
    }

    public static String makeTaskId(String openId, Long flowId) {
        return openId + delimiter + flowId;
    }
}
